package com.asdf.application.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import com.asdf.application.Constants;
import com.asdf.application.Messages;
import com.asdf.application.NetServiceSimulator;
import com.asdf.application.commands.ConnectCommand;
import com.asdf.application.commands.DisconnectCommand;
import com.asdf.application.commands.ExitCommand;
import com.asdf.application.commands.ICommandLine;
import com.asdf.application.commands.InitCommand;
import com.asdf.application.commands.SwitchCommand;
import com.asdf.external.LogWriter;

/**
 * @author Artem Barger
 * 
 * The main class in the program, initiate the system 
 * and waits for user input from command line.
 *
 */
public class NetService
{
	private final static String INIT_COMMAND       = Messages.getString("comman.init"); 
	private final static String SWITCH_COMMAND     = Messages.getString("comman.switch");
	private final static String CONNECT_COMMAND    = Messages.getString("comman.connect");
	private final static String DISCONNECT_COMMAND = Messages.getString("comman.disconnect");
	private final static String EXIT_COMMAND       = Messages.getString("comman.exit");
	
	private Map< String, ICommandLine> switcher = new HashMap< String, ICommandLine>( );
	
	/**
	 * Initialize the system.
	 */
	public NetService( )
	{
		switcher.put( EXIT_COMMAND, 	new ExitCommand( ));
		switcher.put( INIT_COMMAND,   	new InitCommand( ));
		switcher.put( SWITCH_COMMAND, 	new SwitchCommand( ));
		switcher.put( CONNECT_COMMAND,  new ConnectCommand( ));
		switcher.put( DISCONNECT_COMMAND, new DisconnectCommand( ));
	}

	/**
	 * 
	 */
	public void run( )
	{
		BufferedReader input = new BufferedReader( new InputStreamReader( System.in));
		String command = null;
		NetServiceSimulator simulator = new NetServiceSimulator( );
		try
		{
			do
			{
				String line = input.readLine( );
				StringTokenizer tokenizer = new StringTokenizer( line, " ");
				ArrayList<String> parameters = new ArrayList< String>( );

				while ( tokenizer.hasMoreTokens( ))
					parameters.add( tokenizer.nextToken( ));
				
				if (parameters.size() != 0)
					command = parameters.get( 0);
				else
					command = line;

				if ( switcher.containsKey( command))
				{
					switcher.get( command).execute( simulator, parameters);
				}
				else
				{
					LogWriter.getInstance( ).reportError( Constants.UNKNOW_COMMAND_MSG);
				}
			} while ( !command.equalsIgnoreCase( EXIT_COMMAND));
			
		}
		catch ( IOException e )
		{
			e.printStackTrace( );
		}
	}
 	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		NetService service = new NetService( );
		service.run( );
	}

}
